import { useEffect } from "react";
import { Table, Pagination, Space, Divider, Modal, message, Tag } from "antd";
import { Button, Card as SemiCard } from "@douyinfe/semi-ui";
import { useReactive } from "ahooks";
import { useModel } from "umi";
import { AllOutterMembers, OutterToInner, RemoveMember } from "../_graphql";
import EditOutterMemberInfo from "../_modals/edit.outter";
import OutterToInnerApply from "../_modals/to.inner.apply";
import RemoveOutterApply from "../_modals/remove.outter.apply";
import RemoveOutterModal from "../_modals/remove.outter";

const { Column } = Table;

export default function AllMembersPage() {
    const { remoteData, windowInnerHeight, UTCTimeToLocal } = useModel("global");
    const { organizationUuid, remoteOrganizationInfo, organizationInfo } = useModel("organization.info");
    const { setModalVisible, setModalTitle, setModalComponent, setModalStyle, setModalWidth } = useModel("global.modal");
    const { baseInfo, memberInfo } = useModel("person.info");
    const { reviewerRoles } = useModel("application.info");

    const state = useReactive({
        loading: false,
        members: [],
        totalCount: 0,
        pageSize: 20,
        page: 1,
    });

    const loadMembers = async (first, offset) => {
        state.loading = true;
        let res = await remoteData({
            object: "multi-organization-gateway",
            serviceName: "/graphql/public_graphql_service",
            organizationUuid: organizationUuid,
            params: { query: AllOutterMembers, variables: { first: first || state.pageSize, offset: offset || 0 } },
        });
        state.members = res?.a?.nodes || [];
        state.totalCount = res?.a?.totalCount || 0;
        state.loading = false;
    };

    useEffect(() => {
        organizationUuid && loadMembers();
    }, [organizationUuid]);

    const updateMemberInfo = (newData, index) => {
        const newMembers = [...state.members];
        newMembers[index] = { ...newMembers[index], ...newData };
        state.members = newMembers;
    };

    const openEditOutterMember = (record, index) => {
        setModalTitle("编辑外部成员信息");
        setModalStyle({ top: 100 });
        setModalComponent(<EditOutterMemberInfo record={record} index={index} updateMemberInfo={updateMemberInfo} />);
        setModalVisible(true);
    };

    const toInnerApply = async (record) => {
        Modal.confirm({
            content: `确认要把【${record.omName}】转为内部成员吗？`,
            onOk: async () => {
                let res = await remoteData({
                    object: "multi-organization-gateway",
                    serviceName: "/graphql/public_graphql_service",
                    organizationUuid: organizationUuid,
                    params: { query: OutterToInner, variables: { omUuid: record.omUuid } },
                });
                if (res) {
                    message.success(`成功把【${record.omName}】转为内部成员`);
                    loadMembers();
                }
            },
        });
    };

    const removeMemberApply = async (record) => {
        Modal.confirm({
            content: `确认要把【${record.omName}】移除组织吗？`,
            onOk: async () => {
                let res = await remoteData({
                    object: "base-platform-management-service",
                    serviceName: "/api/v1/person/organization/remove",
                    params: { personUuid: record.omUuid, organizationUuid },
                });
                if (res) {
                    res = await remoteData({
                        object: "multi-organization-gateway",
                        serviceName: "/graphql/public_graphql_service",
                        organizationUuid: organizationUuid,
                        params: { query: RemoveMember, variables: { omUuid: record.omUuid } },
                    });

                    if (res) {
                        message.success(`成功把【${record.omName}】移除组织`);
                        loadMembers();
                    }
                }
            },
        });
    };

    const cardBodyHeight = windowInnerHeight - 90 - 20 - 53 - 60;

    return (
        <SemiCard
            title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>外部成员列表</span>}
            headerExtraContent={<Button onClick={() => loadMembers()}>刷新</Button>}
            headerStyle={{ padding: "10px 14px" }}
            shadows="always"
            bordered={false}
            bodyStyle={{ padding: 0, height: cardBodyHeight }}
            footerStyle={{ padding: 0 }}
            footerLine={true}
            footer={
                <div style={{ padding: 14, display: "flex", justifyContent: "space-between" }}>
                    <div></div>
                    <Pagination
                        total={state.totalCount}
                        showTotal={(total, range) => `当前显示第 ${range[0]}-${range[1]} 条，共 ${total} 条`}
                        pageSize={state.pageSize}
                        current={state.page}
                        showSizeChanger={false}
                        onChange={(page, pageSize) => {
                            state.page = page;
                            loadMembers(pageSize, (page - 1) * pageSize);
                        }}
                    />
                </div>
            }
        >
            <Table loading={state.loading} bordered size="small" pagination={false} dataSource={state.members} rowKey="omUuid" scroll={{ y: cardBodyHeight - 40 }}>
                <Column title="序号" align="center" render={(_, r, i) => (state.page - 1) * state.pageSize + i + 1} width={80} />
                <Column title="成员姓名" dataIndex="omName" align="center" />
                <Column title="成员性别" dataIndex="omRoge" align="center" width={100} />
                <Column title="成员生日" dataIndex="omBirt" align="center" width={150} />
                <Column title="所属民族" dataIndex="omNati" align="center" width={100} />
                <Column title="外部组织名称" dataIndex="omEona" align="center" />
                <Column title="外部职位名称" dataIndex="omPosi" align="center" />
                <Column title="加入原由" dataIndex="omCaus" align="center" width={360} />
                <Column title="加入日期" dataIndex="omJoti" align="center" width={120} render={(_) => UTCTimeToLocal(_, "YYYY-MM-DD")} />
                <Column
                    title="成员状态"
                    dataIndex="omAust"
                    align="center"
                    width={100}
                    render={(_) => {
                        //待认证，已认证，重新认证，自己退出，已移除
                        let color;
                        if (_ === "待认证" || _ === "重新认证") color = "processing";
                        if (_ === "已认证") color = "success";
                        if (_ === "已退出" || _ === "已移除") color = "error";
                        return <Tag color={color}>{_}</Tag>;
                    }}
                />
                <Column
                    title="操作"
                    align="center"
                    render={(_, record, index) => {
                        return (
                            <Space size={0} split={<Divider type="vertical" />}>
                                <a onClick={() => openEditOutterMember(record, index)}>编辑</a>
                                {/* <a onClick={() => toInnerApply(record)}>转内部</a> */}
                                {record.omUuid === organizationInfo.superAdministratorUuid ? null : record.omUuid === baseInfo.uuid ? null : (
                                    <a onClick={() => removeMemberApply(record)}>移除</a>
                                )}
                            </Space>
                        );
                    }}
                />
            </Table>
        </SemiCard>
    );
}
